package com.icongyou.enterprise.talent_pool.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.icongyou.enterprise.data_aggregation.entity.AssignmentEntity;
import com.icongyou.enterprise.data_aggregation.service.DataAggregationService;
import com.icongyou.enterprise.talent_pool.entity.StudentAssignmentPerformanceEntity;
import com.icongyou.enterprise.talent_pool.entity.vo.StudentSubmissionInfo;
import com.icongyou.enterprise.talent_pool.mapper.StudentAssignmentPerformanceMapper;
import com.icongyou.enterprise.talent_pool.service.StudentAssignmentPerformanceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class StudentAssignmentPerformanceServiceImpl implements StudentAssignmentPerformanceService {

    private final StudentAssignmentPerformanceMapper studentAssignmentPerformanceMapper;
    private final DataAggregationService dataAggregationService;

    // 缓存上次计算时间
    private LocalDateTime lastCalculationTime = LocalDateTime.now().minusDays(1);

    @Override
    @Transactional
    public void calculateStudentAssignmentPerformanceIncrementally() {
        // 增量指的是对于新出现的任务

        // 获取需要计算的任务ID
        List<String> assignmentIds = studentAssignmentPerformanceMapper.getAssignmentsToCalculate(lastCalculationTime);

        if (assignmentIds.isEmpty()) {
            return;
        }

        // 批量处理任务
        List<StudentAssignmentPerformanceEntity> allPerformances = new ArrayList<>();
        int processedCount = 0;

        for (String assignmentId : assignmentIds) {
            try {
                List<StudentAssignmentPerformanceEntity> assignmentPerformances = calculateAssignmentPerformanceRealtime(assignmentId);
                allPerformances.addAll(assignmentPerformances);

                processedCount++;

                // 每处理10个任务批量插入一次
                if (allPerformances.size() >= 500) {
                    savePerformancesBatch(allPerformances, assignmentIds);
                    allPerformances.clear();
                }

                if (processedCount % 10 == 0) {
                }

            } catch (Exception e) {
            }
        }

        // 保存剩余的学生表现
        if (!allPerformances.isEmpty()) {
            savePerformancesBatch(allPerformances, assignmentIds);
        }

        // 更新最后计算时间
        lastCalculationTime = LocalDateTime.now();

    }


    @Override
    public List<StudentAssignmentPerformanceEntity> calculateAssignmentPerformanceRealtime(String assignmentId) {

        // 获取任务信息
        AssignmentEntity assignment = dataAggregationService.getAssignmentInfo(assignmentId);
        if (assignment == null) {
            return Collections.emptyList();
        }

        // 获取任务提交记录 - 现在返回的是 List<StudentSubmissionInfo>
        List<StudentSubmissionInfo> submissions = studentAssignmentPerformanceMapper.getAssignmentSubmissions(assignmentId);
        if (submissions.isEmpty()) {
            return Collections.emptyList();
        }

        // 按学生分组，取每个学生的最新提交
        Map<String, StudentSubmissionInfo> studentLatestSubmissions = new HashMap<>();

        for (StudentSubmissionInfo submission : submissions) {
            Integer assignmentType = submission.getAssignmentType();
            String teamId = submission.getTeamId();

            try {
                if (assignmentType == 0) {
                    // 个人任务：直接使用student_id
                    String studentId = submission.getStudentId();
                    if (studentId != null) {
                        // 解析个人任务的贡献度（应该是100%）
                        Double contributionRate = parseContributionRate(submission.getContributionRate(), studentId);
                        submission.setIndividualContributionRate(contributionRate != null ? contributionRate : 100.0);

                        // 更新最新提交
                        updateLatestSubmission(studentLatestSubmissions, studentId, submission);
                    }
                } else {
                    // 团队任务：通过team_members找到所有学生，并解析各自的贡献度
                    if (teamId != null) {
                        List<String> teamStudentIds = studentAssignmentPerformanceMapper.getTeamStudentIds(teamId);
                        for (String studentId : teamStudentIds) {
                            Double contributionRate = parseContributionRate(submission.getContributionRate(), studentId);
                            if (contributionRate != null) {
                                // 复制提交记录并为每个学生设置个人贡献度
                                StudentSubmissionInfo studentSubmission = new StudentSubmissionInfo();
                                // 复制所有字段
                                BeanUtils.copyProperties(submission, studentSubmission);
                                studentSubmission.setIndividualContributionRate(contributionRate);
                                updateLatestSubmission(studentLatestSubmissions, studentId, studentSubmission);
                            }
                        }
                    }
                }
            } catch (Exception e) {
            }
        }

        // 计算每个学生的表现得分
        List<StudentAssignmentPerformanceEntity> performances = new ArrayList<>();
        Integer assignmentType = assignment.getAssignmentType();
        Double fullScore = assignment.getFullScore() != null ? assignment.getFullScore().doubleValue() : 100.0;

        for (Map.Entry<String, StudentSubmissionInfo> entry : studentLatestSubmissions.entrySet()) {
            String studentId = entry.getKey();
            StudentSubmissionInfo submission = entry.getValue();

            try {
                Double performanceScore = calculateSingleStudentPerformance(
                        studentId, assignmentId, submission, assignmentType, fullScore);

                if (performanceScore != null) {
                    StudentAssignmentPerformanceEntity performance = new StudentAssignmentPerformanceEntity();
                    performance.setId(UUID.randomUUID().toString());
                    performance.setStudentId(studentId);
                    performance.setAssignmentId(assignmentId);
                    performance.setPerformanceScore(performanceScore);
                    performance.setCalculatedTime(LocalDateTime.now());

                    performances.add(performance);
                }
            } catch (Exception e) {
            }
        }

        return performances;
    }

    /**
     * 更新学生的最新提交记录
     */
    private void updateLatestSubmission(Map<String, StudentSubmissionInfo> studentSubmissions,
                                        String studentId, StudentSubmissionInfo submission) {
        StudentSubmissionInfo existing = studentSubmissions.get(studentId);
        if (existing == null) {
            studentSubmissions.put(studentId, submission);
            return;
        }

        // 比较提交时间，保留最新的
        LocalDateTime existingTime = existing.getSubmissionTime();
        LocalDateTime newTime = submission.getSubmissionTime();

        if (newTime != null && (existingTime == null || newTime.isAfter(existingTime))) {
            studentSubmissions.put(studentId, submission);
        }
    }

    /**
     * 计算单个学生在任务中的表现得分
     */
    private Double calculateSingleStudentPerformance(String studentId, String assignmentId,
                                                     StudentSubmissionInfo submissionInfo,
                                                     Integer assignmentType, Double fullScore) {
        Double individualContributionRate = submissionInfo.getIndividualContributionRate();

        // 基础分数计算
        Double finalScore = submissionInfo.getFinalScore() != null ? submissionInfo.getFinalScore() : 0.0;

        Double baseScore;

        if (assignmentType == 0) {
            // 个人任务：直接使用得分比例
            baseScore = fullScore > 0 ? (finalScore / fullScore) * 100 : 0.0;
        } else {
            // 团队任务：考虑个人贡献度
            String teamId = submissionInfo.getTeamId();

            if (teamId != null && individualContributionRate != null && individualContributionRate > 0) {
                // 获取团队平均贡献值
                Double teamAvgContribution = studentAssignmentPerformanceMapper.getTeamAverageContribution(assignmentId, teamId);
                if (teamAvgContribution != null && teamAvgContribution > 0) {
                    // 基础分数 = (个人贡献度 / 团队平均贡献值) * (团队得分 / 满分) * 80
                    double contributionRatio = individualContributionRate / teamAvgContribution;
                    baseScore = fullScore > 0 ? contributionRatio * (finalScore / fullScore) * 100 : 0.0;
                } else {
                    baseScore = fullScore > 0 ? (finalScore / fullScore) * 100 : 0.0;
                }
            } else {
                baseScore = fullScore > 0 ? (finalScore / fullScore) * 100 : 0.0;
            }
        }

        // 加分项
        double bonusScore = calculateBonusScore(submissionInfo);

        // 计算最终得分（不超过100分）
        double totalScore = baseScore + bonusScore;
        return Math.min(100.0, Math.max(0.0, totalScore));
    }

    /**
     * 计算加分项
     */
    private double calculateBonusScore(StudentSubmissionInfo submission) {
        double bonusScore = 0.0;

        // 教师推荐加分
        Integer isTeacherRecommended = submission.getIsTeacherRecommended();
        if (isTeacherRecommended != null && isTeacherRecommended == 1) {
            bonusScore += 5.0;
        }

        // 点赞加分
        Integer likeCount = submission.getLikeCount();
        if (likeCount != null) {
            bonusScore += likeCount * 0.1;
        }

        // 收藏加分
        Integer favoriteCount = submission.getFavoriteCount();
        if (favoriteCount != null) {
            bonusScore += favoriteCount * 0.2;
        }

        // 按时提交加分
        Integer isLate = submission.getIsLate();
        if (isLate != null && isLate == 0) {
            bonusScore += 2.0;
        }

        return bonusScore;
    }


    /**
     * 解析贡献度JSON，获取指定学生的贡献率
     */
    private Double parseContributionRate(String contributionRateJson, String studentId) {
        if (contributionRateJson == null || studentId == null) {
            return null;
        }

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            List<Map<String, Object>> contributionList = objectMapper.readValue(
                    contributionRateJson,
                    new TypeReference<List<Map<String, Object>>>() {}
            );

            for (Map<String, Object> contribution : contributionList) {
                String contribStudentId = (String) contribution.get("studentId");
                if (studentId.equals(contribStudentId)) {
                    Object rateObj = contribution.get("rate");
                    if (rateObj instanceof Number) {
                        return ((Number) rateObj).doubleValue();
                    }
                }
            }
        } catch (Exception e) {
        }

        return null;
    }

    /**
     * 批量保存学生表现数据
     */
    private void savePerformancesBatch(List<StudentAssignmentPerformanceEntity> performances, List<String> assignmentIds) {
        try {
            // 先删除这些任务已有的记录
            studentAssignmentPerformanceMapper.deleteByAssignmentIds(assignmentIds);

            // 插入新的记录
            studentAssignmentPerformanceMapper.batchInsertStudentAssignmentPerformance(performances);
        } catch (Exception e) {
        }
    }
}